/*
Copyright 2023-2024 API Testing Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

	http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package runner

import (
	_ "embed"
	"fmt"

	"github.com/linuxsuren/api-testing/pkg/logging"

	"io"
	"strconv"

	"github.com/flopp/go-findfont"
	"github.com/linuxsuren/api-testing/pkg/apispec"
	"github.com/signintech/gopdf"
)

var (
	writeLogger = logging.DefaultLogger(logging.LogLevelInfo).WithName("write")
)

type pdfResultWriter struct {
	writer io.Writer
}

// NewPDFResultWriter creates a new PDFResultWriter
func NewPDFResultWriter(writer io.Writer) ReportResultWriter {
	return &pdfResultWriter{writer: writer}
}

// Output writes the PDF base report to target writer
func (w *pdfResultWriter) Output(result []ReportResult) (err error) {
	pdf := gopdf.GoPdf{}
	pdf.Start(gopdf.Config{PageSize: *gopdf.PageSizeA4})

	var fontPath string
	fontPath, err = findfont.Find("DejaVuSerif.ttf")
	if err != nil {
		writeLogger.Error(err, "Failed to find 'ttf'", "path", fontPath)

		if len(findfont.List()) == 0 {
			err = fmt.Errorf("cannot find font")
			writeLogger.Error(err, "No font found")
			return
		}

		fontPath = findfont.List()[0]
	}

	writeLogger.Info("Found font 'ttf'", "path", fontPath)
	err = pdf.AddTTFFont("wts11", fontPath)
	if err != nil {
		writeLogger.Info(err.Error())
		return
	}
	err = pdf.SetFont("wts11", "", 14)
	if err != nil {
		writeLogger.Info(err.Error())
		return
	}

	pdf.AddHeader(func() {
	})
	pdf.AddFooter(func() {
		const X_bias float64 = 101
		pdf.SetXY(X_bias, 825)

		pdf.Text("Generated by github.com/LinuxSuRen/api-testing")
		pdf.AddExternalLink("https://github.com/LinuxSuRen/api-testing", 95+X_bias, 813, 200, 15)

		// pdf.Image("../pkg/runner/data/imgs/gopher.jpg", 500, 780, nil) //print image
	})

	const line_bias float64 = 50
	const Y_start float64 = 100
	for _, api := range result {
		pdf.AddPage()
		pdf.SetXY(50, Y_start)
		pdf.Cell(nil, "API:    "+string(api.API))
		pdf.SetXY(50, Y_start+line_bias)
		pdf.Cell(nil, "Count:  "+strconv.Itoa(api.Count))
		pdf.SetXY(50, Y_start+line_bias*2)
		pdf.Cell(nil, "Average:"+api.Average.String())
		pdf.SetXY(50, Y_start+line_bias*3)
		pdf.Cell(nil, "Max:    "+api.Max.String())
		pdf.SetXY(50, Y_start+line_bias*4)
		pdf.Cell(nil, "Min:    "+api.Min.String())
		pdf.SetXY(50, Y_start+line_bias*5)
		pdf.Cell(nil, "QPS:    "+strconv.Itoa(api.QPS))
		pdf.SetXY(50, Y_start+line_bias*6)
		pdf.Cell(nil, "Error:  "+strconv.Itoa(api.Error))
		pdf.SetXY(50, Y_start+line_bias*7)
		pdf.Cell(nil, "LastErrorMessage:")
		pdf.SetXY(50, Y_start+line_bias*8)
		pdf.Cell(nil, api.LastErrorMessage)

		if api.Error != 0 {
			pdf.Image("../pkg/runner/data/imgs/warn.jpg", 30, Y_start+line_bias*6-5, nil)
		}
	}

	_, err = pdf.WriteTo(w.writer)
	return
}

// WithAPIConverage sets the api coverage
func (w *pdfResultWriter) WithAPICoverage(apiConverage apispec.APICoverage) ReportResultWriter {
	return w
}

func (w *pdfResultWriter) WithResourceUsage([]ResourceUsage) ReportResultWriter {
	return w
}

func (w *pdfResultWriter) GetWriter() io.Writer {
	return w.writer
}
